package club.xiaojiawei.array;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 2022/4/17 16:43
 * @question 69.X的平方根
 * @description 给你一个非负整数 x ，计算并返回 x 的 算术平方根 。由于返回类型是整数，结果只保留 整数部分 ，小数部分将被 舍去 。注意：不允许使用任何内置指数函数和算符，例如 pow(x, 0.5) 或者 x ** 0.5 。
 */
public class SquareRoot69 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println(mySqrt(2147483647));
        System.out.println(System.currentTimeMillis()-start+"ms");
    }

    public static int mySqrt(int x) {
        int size = (Integer.toString(x).length() + 2 - 1) >> 1;
        int left, right = 1;
        for (int i = 0; i < size; i++) {
            right *= 10;
        }
        left = right / 10;
        int middle;
        long temp;
        while (left <= right){
            middle = (left + right) >> 1;
            if ((temp = (long) middle * middle) > (long)x){
                if ((long) (middle - 1) * (middle - 1) <= (long)x){
                    return middle - 1;
                }
                right = middle - 1;
            }else if (temp < (long)x){
                if ((long) (middle + 1) * (middle + 1) > (long)x){
                    return middle;
                }
                left = middle + 1;
            }else {
                return middle;
            }
        }
        return 0;
    }
}
